#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/6/4 17:26
# @Author  : khz_df
# @Site    : 
# @File    : ClientMgr.py
# @Software: ce9nt
import json
import os
import threading

from Client import Client
from selenium import webdriver

from PhpApi import PhpApi


class ClientMgr(object):
    """
    请求服务器包
    """
    def __init__(self):
        self.threads = list()
        self.lock = threading.Lock()
        self.max_id = 0

    def req_account(self):
        self.lock.acquire()
        max_id = self.max_id

        while True:
            json_accounts = PhpApi().req_account(max_id)
            json_accounts = json_accounts.replace('\\', '\\\\')
            obj_accounts = json.loads(json_accounts, encoding='utf-8')
            if obj_accounts['status'] != 200:
                print('【Error】 status != 200')
                max_id = max_id + 1
                continue

            if len(obj_accounts['data']) > 0:
                self.max_id = int(obj_accounts['data'][-1]['id'])
            self.lock.release()

            if len(obj_accounts['data']) == 0:
                return None
            else:
                return obj_accounts['data']

    def deal_unit(self, max_id):
        json_accounts = PhpApi().req_account(max_id)
        json_accounts = json_accounts.replace('\\', '\\\\')
        obj_accounts = json.loads(json_accounts, encoding='utf-8')
        if obj_accounts['status'] != 200:
            print('【Error】 status != 200')
            return max_id + 1

        if len(obj_accounts['data']) == 0:
            return -1

        for unit in obj_accounts['data']:
            # print(unit)
            shelf_id = int(unit['id'])
            if shelf_id > max_id:
                max_id = shelf_id

            try:
                Client(unit).Run()
            except Exception as e:
                print('【ClientMgr】 except Exception, deal_unit,', e)

        # 关闭所有tab页面
        if True:
            browser = webdriver.Chrome()
            browser.quit()

        return max_id

    @staticmethod
    def fn_thread(index):
        while True:
            obj_accounts = g_mgr.req_account()
            if len(obj_accounts) == 0:
                return

            for unit in obj_accounts:
                try:
                    Client(unit).Run()
                except Exception as e:
                    print('【ClientMgr】 except Exception, deal_unit,', e)

    def Run(self):
        max_id = 0

        # 启动5个线程
        event_obj = threading.Event()     #创建一个事件
        for i in range(5):
            t = threading.Thread(target=ClientMgr.fn_thread, args=(i, ))
            t.start()
            self.threads.append(t)

        for t in self.threads:
            t.join()

        return


def foo():
    threading.Thread()


g_mgr = ClientMgr()


def main():
    g_mgr.Run()


if __name__ == "__main__":
    print("------------------    Enter __main__    ------------------")

    print(u"[Current work directory is : ]\t" + os.getcwd())
    print(u"[Current process ID is : ]\t" + str(os.getpid()))
    print("\n")
    main()

    print("------------------    Leave __main__    ------------------")
